/**
 * Created by HEKI on 8/24/2016.
 */
const mongoose = require("mongoose");
var Client = mongoose.model("client");


exports.userRegist = function (req, res) {
    console.log("用户注册");
    var registTel = req.body.cTel;
    console.log(registTel);
    Client.findOne({cTel: registTel}, function (err, client) {
        if (client) {
            res.json({error: "电话已注册!"})
        }
        else {
            var client = new Client(req.body);
            console.log(client);
            client.save(function (err) {
                if (!err) {
                    var tempClient = {_id:client._id,cPersonName:client.cPersonName,cTel:client.cTel,cLocation:client.cLocation};
                    req.session.client = tempClient;
                    res.json(tempClient);
                }
                else {
                    res.json({error: "注册失败!"});
                }
            });
        }
    });

}

exports.updateUserInfo = function (req, res) {
    console.log("用户更新信息");
    var loginclient  = req.session.client;
    Client.findByIdAndUpdate(loginclient._id,req.body,function (err,oldClient) {
        if(!err){
            Client.findOne({_id:loginclient._id},function (err,newClient) {
                var tempClient = {_id:newClient._id,cPersonName:newClient.cPersonName,cTel:newClient.cTel,cLocation:newClient.cLocation};
                req.session.client = tempClient;
                res.json(tempClient);
            })
        }
        else {
            res.json({error:"更新失败!"})
        }
    })
}

exports.userLogin = function (req, res) {
    console.log("用户登录");
    Client.findOne({cTel: req.body.cTel}, function (err, client) {
        if (client) {
            if (client.cPassword == req.body.cPassword) {
                var tempClient = {_id:client._id,cPersonName:client.cPersonName,cTel:client.cTel,cLocation:client.cLocation};
                req.session.client = tempClient;
                res.json(tempClient);
            } else
                res.json({error: "密码错误!"});
        }
        else {
            res.json({error: "用户名不存在!"});
        }
    });
}

exports.userLogout = function (req, res) {
    console.log("用户登出");
    req.session.client = null;
    req.session.foodCart={};
    res.json({success:"成功登出"});
}

exports.getUserLoginStatus = function (req, res) {
    console.log("判断用户是否登录");
    if(req.session.client){
        res.json(req.session.client);
    }
    else{
        res.json({error:"用户未登录!"});
    }
}